<template>
  <a-card :bordered="false">
    <div class="route-planning">
      <!-- 左侧控制面板 -->
      <div class="control-panel">
        <a-tabs v-model="activeTab" defaultActiveKey="1">
          <a-tab-pane key="1" tab="规划航线">
            <a-form layout="vertical">
              <!-- 航线基本信息 -->
              <a-form-item label="航线名称">
                <a-input v-model="routeName" placeholder="请输入航线名称" />
              </a-form-item>

              <!-- 添加无人机速度设置 -->
              <a-form-item label="飞行速度 (米/秒)">
                <a-input-number
                  v-model="droneSpeed"
                  :min="1"
                  :max="20"
                  :step="0.5"
                  style="width: 100%"
                />
              </a-form-item>

              <!-- 航点列表 -->
              <div class="waypoints-list">
                <div class="section-title">航点列表</div>
                <a-table
                  size="small"
                  :columns="columns"
                  :dataSource="waypoints"
                  :pagination="false"
                  :locale="{emptyText: '暂无航点'}"
                  :rowKey="record => String(record.id)"
                >
                  <template slot="action" slot-scope="text, record, index">
                    <a-space>
                      <a-button type="link" size="small" @click="editWaypoint(index)">编辑</a-button>
                      <a-button type="link" size="small" @click="removeWaypoint(index)">删除</a-button>
                    </a-space>
                  </template>
                  <template slot="altitude" slot-scope="text">
                    {{ text }}米
                  </template>
                  <template slot="hoverTime" slot-scope="text">
                    {{ text }}秒
                  </template>
                </a-table>
              </div>

              <!-- 操作按钮 -->
              <div class="control-buttons">
                <a-button type="primary" @click="startPlanning" :disabled="isPlanning">
                  开始规划
                </a-button>
                <a-button @click="clearWaypoints" :disabled="isPlanning || !waypoints.length">
                  清除航点
                </a-button>
                <a-button
                  type="primary"
                  @click="previewRoute"
                  :disabled="waypoints.length < 2"
                  ghost
                >
                  预览航线
                </a-button>
                <a-button
                  type="primary"
                  @click="saveRoute"
                  :disabled="!waypoints.length || !routeName"
                  ghost
                >
                  保存航线
                </a-button>
                <a-dropdown>
                  <a-menu slot="overlay">
                    <a-menu-item key="1" @click="exportRoute">
                      <a-icon type="export" />导出航线
                    </a-menu-item>
                    <a-menu-item key="2" @click="$refs.importInput.click()">
                      <a-icon type="import" />导入航线
                    </a-menu-item>
                  </a-menu>
                  <a-button>
                    更多操作 <a-icon type="down" />
                  </a-button>
                </a-dropdown>
              </div>

              <!-- 隐藏的文件输入框 -->
              <input
                type="file"
                ref="importInput"
                style="display: none"
                accept=".json"
                @change="handleImportFile"
              >
            </a-form>
          </a-tab-pane>

          <a-tab-pane key="2" tab="航线列表">
            <div class="route-list-container">
              <a-list
                :dataSource="routeList"
                size="small"
                :locale="{emptyText: '暂无航线'}"
                :rowKey="item => String(item.id)"
              >
                <a-list-item slot="renderItem" slot-scope="route">
                  <a-card size="small">
                    <div class="route-header">
                      <span class="route-name">{{ route.name }}</span>
                      <a-tag :color="getStatusColor(route.status)">
                        {{ getStatusText(route.status) }}
                      </a-tag>
                    </div>
                    <div class="route-info">
                      <div class="info-item">
                        <a-icon type="environment" />
                        <span>航点: {{ route.waypoints ? route.waypoints.length : 0 }}</span>
                      </div>
                      <div class="info-item">
                        <a-icon type="clock-circle" />
                        <span>预计时间: {{ formatTime(calculateTotalExecutionTime(route)) }}</span>
                      </div>
                    </div>
                    <div class="route-actions">
                      <a-button-group>
                        <a-tooltip title="查看航线">
                          <a-button size="small" @click="showRoute(route)">
                            <a-icon type="eye" />
                          </a-button>
                        </a-tooltip>
                        <a-tooltip title="执行航线">
                          <a-button
                            size="small"
                            type="primary"
                            @click="executeRoute(route)"
                            :disabled="route.status === 'executing'"
                          >
                            <a-icon type="play-circle" />
                          </a-button>
                        </a-tooltip>
                        <a-tooltip title="删除航线">
                          <a-button
                            size="small"
                            type="danger"
                            @click="deleteRoute(route)"
                            :disabled="route.status === 'executing'"
                          >
                            <a-icon type="delete" />
                          </a-button>
                        </a-tooltip>
                      </a-button-group>
                    </div>
                  </a-card>
                </a-list-item>
              </a-list>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>

      <!-- 右侧地图容器 -->
      <div class="map-container">
        <div id="map" class="map"></div>
        <div v-if="mapError" class="error-message">
          <a-alert type="error" :message="mapError" banner />
        </div>
        <div class="map-controls" v-if="!mapError">
          <a-button-group style="margin-bottom: 10px">
            <a-button @click="toggleView" :loading="viewChanging">
              {{ is3D ? '2D视图' : '3D视图' }}
            </a-button>
            <a-button @click="toggleSatellite">
              {{ isSatellite ? '标准地图' : '卫星地图' }}
            </a-button>
          </a-button-group>
        </div>

        <div v-if="isPlanning" class="planning-tips">
          <a-alert
            message="点击地图添加航点，右键结束规划"
            type="info"
            showIcon
            banner
          />
        </div>

        <!-- 执行信息覆盖层 -->
        <div class="execution-info-overlay" v-if="activeExecutions.length > 0">
          <div v-for="task in activeExecutions" :key="task.id" class="execution-info-card">
            <div class="execution-info-header">
              <span>{{ task.name }}</span>
              <a-tag :color="getExecutionStatusColor(task)">
                {{ getExecutionStatusText(task) }}
              </a-tag>
            </div>
            <div class="execution-info-progress">
              <a-progress
                :percent="calculateProgress(task)"
                :status="getProgressStatus(task)"
                size="small"
                :stroke-color="progressStrokeColor"
              />
            </div>
            <div class="execution-info-details">
              <div class="detail-row">
                <span>航点: {{ task.currentPoint + 1 }}/{{ task.totalPoints }}</span>
                <span>{{ formatTime(task.currentTime) }}/{{ formatTime(task.totalTime) }}</span>
              </div>
              <div class="detail-row">
                <span>速度: {{ task.speed }}m/s</span>
                <span>高度: {{ Math.round(task.altitude) }}m</span>
              </div>
              <div class="detail-row">
                <span>剩余: {{ formatTime(calculateRemainingTime(task)) }}</span>
              </div>
            </div>
            <div class="execution-info-actions">
              <a-button-group size="small">
                <a-button
                  @click="togglePause(task)"
                  :type="task.paused ? 'primary' : 'default'"
                >
                  <a-icon :type="task.paused ? 'play-circle' : 'pause'" />
                </a-button>
                <a-button
                  @click="stopTask(task)"
                  type="danger"
                >
                  <a-icon type="stop" />
                </a-button>
              </a-button-group>
            </div>
          </div>
        </div>
      </div>

      <!-- 编辑航点对话框 -->
      <a-modal
        v-model="editModalVisible"
        title="编辑航点"
        @ok="handleEditOk"
        @cancel="handleEditCancel"
        :maskClosable="false"
        :keyboard="false"
        :inert="editModalVisible ? null : ''"
      >
        <a-form :form="editForm" layout="vertical">
          <a-form-item label="航点高度(米)">
            <a-input-number
              v-decorator="[
                'altitude',
                {
                  initialValue: currentWaypoint.altitude,
                  rules: [{ required: true, message: '请输入航点高度' }]
                }
              ]"
              :min="0"
              :max="500"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item label="悬停时间(秒)">
            <a-input-number
              v-decorator="[
                'hoverTime',
                {
                  initialValue: currentWaypoint.hoverTime,
                  rules: [{ required: true, message: '请输入悬停时间' }]
                }
              ]"
              :min="0"
              :max="300"
              style="width: 100%"
            />
          </a-form-item>
        </a-form>
      </a-modal>

      <!-- 添加预览控制面板 -->
      <a-modal
        v-model="previewModalVisible"
        title="航线预览"
        @ok="stopPreview"
        @cancel="stopPreview"
        :maskClosable="false"
        :keyboard="false"
        :inert="previewModalVisible ? null : ''"
      >
        <div class="preview-controls">
          <div class="preview-info">
            <p>当前航点: {{ currentPreviewPoint + 1 }}/{{ waypoints.length }}</p>
            <p>预计飞行时间: {{ estimatedFlightTime }}秒</p>
            <div class="progress-wrapper">
              <a-progress
                :percent="previewProgress"
                :status="previewStatus"
                :stroke-color="progressStrokeColor"
              />
              <p class="progress-text">已完成: {{ formatTime(currentPreviewTime) }} / {{ formatTime(estimatedFlightTime) }}</p>
            </div>
          </div>
          <div class="preview-buttons">
            <a-button-group>
              <a-button @click="stopPreview">
                <a-icon type="stop" />停止
              </a-button>
              <a-button @click="togglePreview">
                <a-icon :type="isPreviewPlaying ? 'pause' : 'play-circle'" />
                {{ isPreviewPlaying ? '暂停' : '播放' }}
              </a-button>
            </a-button-group>
          </div>
        </div>
      </a-modal>

      <!-- 添加导入确认对话框 -->
      <a-modal
        v-model="importModalVisible"
        title="导入航线"
        @ok="confirmImport"
        @cancel="cancelImport"
        :maskClosable="false"
        :keyboard="false"
        :inert="importModalVisible ? null : ''"
      >
        <template v-if="importData">
          <p>确定要导入以下航线吗？</p>
          <p><strong>航线名称：</strong>{{ importData.name }}</p>
          <p><strong>航点数量：</strong>{{ importData.waypoints ? importData.waypoints.length : 0 }}</p>
          <p><strong>创建时间：</strong>{{ formatDate(importData.createdAt) }}</p>
        </template>
      </a-modal>
    </div>
  </a-card>
</template>

<script>
export default {
  name: 'RoutePlanning',
  data () {
    return {
      map: null,
      is3D: true,
      isSatellite: false,
      satelliteLayer: null,
      roadNetLayer: null,
      mapError: null,
      viewChanging: false,
      routeName: '',
      waypoints: [],
      columns: [
        {
          title: '编号',
          dataIndex: 'id',
          key: 'id'
        },
        {
          title: '经度',
          dataIndex: 'lng',
          key: 'lng'
        },
        {
          title: '纬度',
          dataIndex: 'lat',
          key: 'lat'
        },
        {
          title: '高度',
          dataIndex: 'altitude',
          key: 'altitude',
          scopedSlots: { customRender: 'altitude' }
        },
        {
          title: '悬停',
          dataIndex: 'hoverTime',
          key: 'hoverTime',
          scopedSlots: { customRender: 'hoverTime' }
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      isPlanning: false,
      markers: [],
      polyline: null,
      nextWaypointId: 1,
      tempMarkers: [],
      tempPolyline: null,
      controlBar: null,
      editModalVisible: false,
      currentWaypoint: {
        id: null,
        altitude: 100,
        hoverTime: 0
      },
      editingIndex: -1,
      previewModalVisible: false,
      isPreviewPlaying: false,
      currentPreviewPoint: 0,
      previewMarker: null,
      previewTimer: null,
      estimatedFlightTime: 0,
      droneSpeed: 5, // 默认无人机速度 5m/s
      importData: null,
      importModalVisible: false,
      currentPreviewTime: 0, // 当前预览时间
      previewInterval: null, // 进度更新定时器
      progressStrokeColor: { '0%': '#108ee9', '100%': '#87d068' },
      routeList: [], // 航线列表
      loading: false,
      activeExecutions: [], // 活动执行任务列表
      executionIntervals: {}, // 执行任务定时器
      activeTab: '1',
      previewProgress: 0,
      previewStatus: 'normal',
      searchKeyword: '',
      filterStatus: '',
      droneMarkers: {}, // 存储每个任务的无人机标记
      executionPolylines: {} // 存储每个任务的执行路线
    }
  },
  beforeCreate () {
    this.editForm = this.$form.createForm(this)
  },
  mounted () {
    // 修改 mounted 钩子，确保在组件完全挂载后初始化地图
    setTimeout(() => {
      // 检查AMap是否已加载
      if (typeof AMap === 'undefined') {
        this.mapError = '高德地图API未加载，请检查网络连接或API密钥配置'
        console.error('AMap is not defined.')

        this.loadAMapScript()
        return
      }

      try {
        this.initMap()
      } catch (error) {
        console.error('地图初始化错误:', error)
        this.mapError = `地图初始化失败: ${error.message}`
      }
    }, 300) // 给予300ms延迟确保DOM已完全渲染

    this.initExecutionData()
  },
  methods: {
    loadAMapScript () {
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.async = true
      // 加载更多插件，以支持3D视图和地图控件
      script.src = 'https://webapi.amap.com/maps?v=2.0&key=2d33ca727354eb67d75cb29743d39f10&plugin=Map3D,AMap.Scale,AMap.ToolBar,AMap.ControlBar'

      script.onerror = () => {
        this.mapError = '高德地图API加载失败，请检查网络连接'
      }

      script.onload = () => {
        if (typeof AMap !== 'undefined') {
          this.mapError = null
          this.initMap()
        }
      }

      document.head.appendChild(script)
    },

    initMap () {
      // 延迟初始化，确保容器已渲染
      this.$nextTick(() => {
        // 确保地图容器存在
        const container = document.getElementById('map')
        if (!container) {
          console.error('地图容器不存在，将在下一个渲染周期重试')
          setTimeout(() => this.initMap(), 500) // 500ms后重试
          return
        }

        try {
          // 初始化地图
          this.map = new AMap.Map('map', {
            zoom: 12,
            center: [106.504962, 29.533155],
            viewMode: this.is3D ? '3D' : '2D',
            pitch: this.is3D ? 45 : 0,
            mapStyle: 'amap://styles/normal'
          })

          // 预加载所有可能需要的插件
          this.map.plugin([
            'AMap.ToolBar',
            'AMap.Scale',
            'AMap.ControlBar',
            'AMap.MapType'
          ], () => {
            // 添加基础控件
            this.map.addControl(new AMap.ToolBar())
            this.map.addControl(new AMap.Scale())

            // 如果是3D模式，添加控制条
            if (this.is3D) {
              this.addControlBar()
            }

            // 预加载卫星图层
            this.satelliteLayer = new AMap.TileLayer.Satellite()
            this.roadNetLayer = new AMap.TileLayer.RoadNet()
          })
        } catch (error) {
          console.error('地图初始化失败:', error)
          this.mapError = `地图初始化失败: ${error.message}`
        }
      })
    },

    // 修改 addControlBar 方法，检查 ControlBar 是否可用
    addControlBar () {
      if (!this.map) return

      try {
        // 检查 ControlBar 是否可用
        if (!AMap.ControlBar) {
          console.warn('AMap.ControlBar 不可用，可能需要加载插件')

          // 尝试加载 ControlBar 插件
          this.map.plugin(['AMap.ControlBar'], () => {
            if (AMap.ControlBar) {
              this.createControlBar()
            } else {
              console.error('无法加载 AMap.ControlBar 插件')
            }
          })
          return
        }

        this.createControlBar()
      } catch (error) {
        console.error('添加3D控制条失败:', error)
      }
    },

    // 创建控制条的方法
    createControlBar () {
      if (this.controlBar) return

      try {
        this.controlBar = new AMap.ControlBar({
          position: {
            top: '10px',
            right: '10px'
          }
        })
        this.map.addControl(this.controlBar)
      } catch (error) {
        console.error('创建控制条失败:', error)
      }
    },

    // 修改切换视图方法
    toggleView () {
      if (!this.map) return

      this.viewChanging = true

      try {
        // 保存当前中心点和缩放级别
        const center = this.map.getCenter()
        const zoom = this.map.getZoom()

        // 切换3D/2D模式
        this.is3D = !this.is3D

        // 使用 setStatus 方法替代 setViewMode
        this.map.setStatus({
          viewMode: this.is3D ? '3D' : '2D',
          jogEnable: this.is3D,
          pitchEnable: this.is3D,
          rotateEnable: this.is3D
        })

        // 设置俯仰角
        if (this.is3D) {
          this.map.setPitch(45)
          this.addControlBar()
        } else {
          this.map.setPitch(0)
          this.removeControlBar()
        }

        // 恢复中心点和缩放级别
        this.map.setCenter(center)
        this.map.setZoom(zoom)

        this.$message.success(`已切换至${this.is3D ? '3D' : '2D'}视图`)
      } catch (error) {
        console.error('切换视图模式失败:', error)
        this.$message.error('切换视图失败，此浏览器可能不支持3D模式')
      } finally {
        this.viewChanging = false
      }
    },

    // 添加移除控制条方法（之前被删除了）
    removeControlBar () {
      if (!this.map || !this.controlBar) return

      try {
        this.map.removeControl(this.controlBar)
        this.controlBar = null
      } catch (error) {
        console.error('移除3D控制条失败:', error)
      }
    },

    // 修改切换卫星地图方法
    toggleSatellite () {
      if (!this.map) return

      try {
        // 确保图层已初始化
        if (!this.satelliteLayer) {
          this.satelliteLayer = new AMap.TileLayer.Satellite()
        }
        if (!this.roadNetLayer) {
          this.roadNetLayer = new AMap.TileLayer.RoadNet()
        }

        this.isSatellite = !this.isSatellite

        if (this.isSatellite) {
          // 切换到卫星图
          this.map.add([this.satelliteLayer, this.roadNetLayer])
        } else {
          // 切换到标准图
          this.map.remove([this.satelliteLayer, this.roadNetLayer])
        }

        this.$message.success(`已切换至${this.isSatellite ? '卫星' : '标准'}地图`)
      } catch (error) {
        console.error('切换地图图层失败:', error)
        this.$message.error('切换地图图层失败')
      }
    },

    // 重置地图视图
    resetMapView () {
      if (!this.map) return

      try {
        // 重置中心点和缩放级别
        this.map.setCenter([106.504962, 29.533155])
        this.map.setZoom(12)

        // 如果是3D模式，重置俯仰角和旋转角
        if (this.is3D) {
          this.map.setPitch(45)
          this.map.setRotation(0)
        }

        console.log('地图视图已重置')
      } catch (error) {
        console.error('重置地图视图失败:', error)
      }
    },

    startPlanning () {
      if (!this.routeName) {
        this.$message.warning('请先输入航线名称')
        return
      }

      this.isPlanning = true
      // 绑定地图点击事件
      this.map.on('click', this.handleMapClick)
      this.map.on('rightclick', this.handleMapRightClick)
    },

    handleMapClick (e) {
      if (!this.isPlanning) return

      try {
        const position = e.lnglat
        const marker = new AMap.Marker({
          position: [position.getLng(), position.getLat()],
          label: {
            content: `航点${this.nextWaypointId}`,
            direction: 'top'
          },
          animation: 'AMAP_ANIMATION_DROP'
        })

        this.map.add(marker)
        this.tempMarkers.push(marker)

        // 更新航点列表，添加高度和悬停时间
        this.waypoints.push({
          id: this.nextWaypointId,
          lng: position.getLng().toFixed(6),
          lat: position.getLat().toFixed(6),
          altitude: 100, // 默认高度100米
          hoverTime: 0 // 默认悬停0秒
        })

        this.nextWaypointId++
        this.updateTempPolyline()
      } catch (error) {
        console.error('添加航点失败:', error)
        this.$message.error('添加航点失败')
      }
    },

    handleMapRightClick () {
      if (!this.isPlanning || this.tempMarkers.length < 2) return
      this.finishPlanning()
    },

    updateTempPolyline () {
      if (this.tempMarkers.length < 2) return

      try {
        const path = this.tempMarkers.map(marker => marker.getPosition())

        if (this.tempPolyline) {
          this.tempPolyline.setPath(path)
        } else {
          this.tempPolyline = new AMap.Polyline({
            path,
            strokeColor: '#3366FF',
            strokeWeight: 4,
            strokeStyle: 'solid',
            showDir: true
          })
          this.map.add(this.tempPolyline)
        }
      } catch (error) {
        console.error('更新航线失败:', error)
      }
    },

    finishPlanning () {
      this.isPlanning = false

      // 解绑地图事件
      this.map.off('click', this.handleMapClick)
      this.map.off('rightclick', this.handleMapRightClick)

      // 保存航线
      this.markers = this.tempMarkers
      this.polyline = this.tempPolyline

      // 重置临时变量
      this.tempMarkers = []
      this.tempPolyline = null

      this.$message.success('航线规划完成')
    },

    clearWaypoints () {
      // 清除地图上的标记
      if (this.markers && this.markers.length) {
        this.map.remove(this.markers)
        this.markers = []
      }

      // 清除地图上的路线
      if (this.polyline) {
        this.map.remove(this.polyline)
        this.polyline = null
      }

      // 清空航点数组
      this.waypoints = []

      // 重置临时标记和路线
      if (this.tempMarkers && this.tempMarkers.length) {
        this.map.remove(this.tempMarkers)
        this.tempMarkers = []
      }

      if (this.tempPolyline) {
        this.map.remove(this.tempPolyline)
        this.tempPolyline = null
      }
    },

    editWaypoint (index) {
      const waypoint = this.waypoints[index]
      this.currentWaypoint = { ...waypoint }
      this.editingIndex = index
      this.editModalVisible = true

      this.$nextTick(() => {
        this.editForm.setFieldsValue({
          altitude: waypoint.altitude,
          hoverTime: waypoint.hoverTime
        })
      })
    },

    removeWaypoint (index) {
      // 移除地图上的标记
      if (this.markers[index]) {
        this.map.remove(this.markers[index])
        this.markers.splice(index, 1)
      }

      // 移除航点数据
      this.waypoints.splice(index, 1)

      // 重新计算航线
      if (this.markers.length >= 2) {
        const path = this.markers.map(marker => marker.getPosition())
        this.polyline.setPath(path)
      } else if (this.polyline) {
        this.map.remove(this.polyline)
        this.polyline = null
      }
    },

    // 处理编辑确认
    handleEditOk () {
      this.editForm.validateFields((err, values) => {
        if (!err) {
          // 更新航点数据
          this.waypoints[this.editingIndex] = {
            ...this.waypoints[this.editingIndex],
            ...values
          }

          // 更新标记的标签
          const marker = this.markers[this.editingIndex]
          if (marker) {
            marker.setLabel({
              content: `航点${this.waypoints[this.editingIndex].id}\n${values.altitude}米`,
              direction: 'top'
            })
          }

          this.editModalVisible = false
          this.$message.success('航点更新成功')
        }
      })
    },

    // 处理编辑取消
    handleEditCancel () {
      this.editModalVisible = false
      this.editForm.resetFields()
    },

    // 计算预计飞行时间
    calculateFlightTime () {
      if (this.waypoints.length < 2) return 0

      let totalTime = 0
      let totalDistance = 0

      // 计算航点间距离和悬停时间
      for (let i = 0; i < this.waypoints.length - 1; i++) {
        const start = new AMap.LngLat(this.waypoints[i].lng, this.waypoints[i].lat)
        const end = new AMap.LngLat(this.waypoints[i + 1].lng, this.waypoints[i + 1].lat)

        // 计算两点间距离（米）
        const distance = start.distance(end)
        totalDistance += distance

        // 添加悬停时间
        totalTime += this.waypoints[i].hoverTime
      }

      // 添加最后一个航点的悬停时间
      totalTime += this.waypoints[this.waypoints.length - 1].hoverTime

      // 计算飞行时间（距离/速度）
      totalTime += totalDistance / this.droneSpeed

      return Math.round(totalTime)
    },

    // 开始预览航线
    previewRoute () {
      if (this.waypoints.length < 2) return

      this.previewModalVisible = true
      this.currentPreviewPoint = 0
      this.currentPreviewTime = 0
      this.estimatedFlightTime = this.calculateFlightTime()

      // 创建预览标记
      this.previewMarker = new AMap.Marker({
        position: [this.waypoints[0].lng, this.waypoints[0].lat],
        icon: new AMap.Icon({
          image: '', // 这里是您提供的无人机图标的 base64 编码
          // 设置图标大小
          size: new AMap.Size(32, 32),
          imageSize: new AMap.Size(32, 32)
        }),
        angle: 0,
        offset: new AMap.Pixel(-16, -16)
      })

      this.map.add(this.previewMarker)
      this.togglePreview()
    },

    // 切换预览状态（播放/暂停）
    togglePreview () {
      this.isPreviewPlaying = !this.isPreviewPlaying

      if (this.isPreviewPlaying) {
        this.moveToNextPoint()
        // 启动进度更新
        this.previewInterval = setInterval(() => {
          if (this.currentPreviewTime < this.estimatedFlightTime) {
            this.currentPreviewTime++
            this.updatePreviewProgress() // 更新进度
          } else {
            this.stopPreview()
          }
        }, 1000)
      } else {
        // 暂停时清除定时器
        if (this.previewTimer) {
          clearTimeout(this.previewTimer)
        }
        if (this.previewInterval) {
          clearInterval(this.previewInterval)
        }
      }
    },

    // 移动到下一个航点
    moveToNextPoint () {
      if (!this.isPreviewPlaying || this.currentPreviewPoint >= this.waypoints.length - 1) {
        this.isPreviewPlaying = false
        return
      }

      const current = this.waypoints[this.currentPreviewPoint]
      const next = this.waypoints[this.currentPreviewPoint + 1]

      // 计算移动时间（基于距离和速度）
      const start = new AMap.LngLat(current.lng, current.lat)
      const end = new AMap.LngLat(next.lng, next.lat)
      const distance = start.distance(end)
      const moveTime = (distance / this.droneSpeed) * 1000 // 转换为毫秒

      // 计算方向角度
      const angle = Math.atan2(
        next.lat - current.lat,
        next.lng - current.lng
      ) * 180 / Math.PI

      // 设置标记角度
      this.previewMarker.setAngle(angle)

      // 使用动画移动标记
      this.previewMarker.moveTo(
        [next.lng, next.lat],
        {
          duration: moveTime,
          delay: current.hoverTime * 1000 // 考虑悬停时间
        }
      )

      // 设置下一个航点的定时器
      this.previewTimer = setTimeout(() => {
        this.currentPreviewPoint++
        this.moveToNextPoint()
      }, moveTime + current.hoverTime * 1000)
    },

    // 停止预览
    stopPreview () {
      this.isPreviewPlaying = false
      if (this.previewTimer) {
        clearTimeout(this.previewTimer)
      }
      if (this.previewInterval) {
        clearInterval(this.previewInterval)
      }
      if (this.previewMarker) {
        this.map.remove(this.previewMarker)
        this.previewMarker = null
      }
      this.previewModalVisible = false
      this.currentPreviewPoint = 0
      this.currentPreviewTime = 0
      this.previewProgress = 0
      this.previewStatus = 'normal'
    },

    // 保存航线
    saveRoute () {
      if (!this.routeName.trim()) {
        this.$message.error('请输入航线名称')
        return
      }

      if (this.waypoints.length < 2) {
        this.$message.error('航线至少需要2个航点')
        return
      }

      // 创建航线对象
      const newRoute = {
        id: Date.now().toString(),
        name: this.routeName,
        waypoints: [...this.waypoints],
        status: 'draft',
        createdAt: new Date().toISOString(),
        speed: this.droneSpeed // 保存设置的速度
      }

      // 添加到航线列表
      this.routeList.push(newRoute)

      // 保存到本地存储
      this.saveRoutesToStorage()

      // 清空表单
      this.resetForm()

      // 切换到航线列表标签
      this.activeTab = '2'

      this.$message.success('航线保存成功')
    },

    // 导出航线
    exportRoute () {
      if (!this.routeName || !this.waypoints.length) {
        this.$message.warning('请先创建航线')
        return
      }

      try {
        const routeData = {
          name: this.routeName,
          waypoints: this.waypoints,
          createdAt: new Date().toISOString()
        }

        // 创建 Blob 对象
        const blob = new Blob([JSON.stringify(routeData, null, 2)], {
          type: 'application/json'
        })

        // 创建下载链接
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `${this.routeName}-${this.formatDate(new Date())}.json`

        // 触发下载
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)

        this.$message.success('航线导出成功')
      } catch (error) {
        console.error('导出航线失败:', error)
        this.$message.error('导出航线失败')
      }
    },

    // 处理文件导入
    handleImportFile (event) {
      const file = event.target.files[0]
      if (!file) return

      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const data = JSON.parse(e.target.result)
          if (!this.validateImportData(data)) {
            throw new Error('无效的航线数据格式')
          }
          this.importData = data
          this.importModalVisible = true
        } catch (error) {
          console.error('解析导入文件失败:', error)
          this.$message.error('导入失败：无效的航线数据文件')
        }
      }
      reader.onerror = () => {
        this.$message.error('读取文件失败')
      }
      reader.readAsText(file)
      event.target.value = ''
    },

    // 验证导入数据格式
    validateImportData (data) {
      if (!data || typeof data !== 'object') return false
      if (!data.name || typeof data.name !== 'string') return false
      if (!Array.isArray(data.waypoints)) return false

      // 验证每个航点的数据格式
      return data.waypoints.every(point => {
        return (
          typeof point.id === 'number' &&
          typeof point.lng === 'string' &&
          typeof point.lat === 'string' &&
          typeof point.altitude === 'number' &&
          typeof point.hoverTime === 'number'
        )
      })
    },

    // 确认导入
    confirmImport () {
      try {
        // 清除现有航线
        this.clearWaypoints()

        // 设置新的航线数据
        this.routeName = this.importData.name
        this.waypoints = this.importData.waypoints

        // 在地图上显示航点和航线
        this.importData.waypoints.forEach(point => {
          const marker = new AMap.Marker({
            position: [point.lng, point.lat],
            label: {
              content: `航点${point.id}\n${point.altitude}米`,
              direction: 'top'
            }
          })
          this.markers.push(marker)
          this.map.add(marker)
        })

        // 绘制航线
        if (this.waypoints.length >= 2) {
          const path = this.waypoints.map(point => [point.lng, point.lat])
          this.polyline = new AMap.Polyline({
            path,
            strokeColor: '#3366FF',
            strokeWeight: 4,
            strokeStyle: 'solid',
            showDir: true
          })
          this.map.add(this.polyline)
        }

        // 调整地图视野以显示整条航线
        this.map.setFitView([...this.markers])

        this.importModalVisible = false
        this.$message.success('航线导入成功')
      } catch (error) {
        console.error('导入航线失败:', error)
        this.$message.error('导入航线失败')
      }
    },

    // 取消导入
    cancelImport () {
      this.importModalVisible = false
      setTimeout(() => {
        this.importData = null
      }, 300) // 等待对话框关闭动画完成后再清空数据
    },

    // 格式化日期
    formatDate (date) {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
    },

    // 更新预览进度
    updatePreviewProgress () {
      if (this.estimatedFlightTime <= 0) {
        this.previewProgress = 0
      } else {
        this.previewProgress = Math.min(100, (this.currentPreviewTime / this.estimatedFlightTime) * 100)
      }
      if (this.previewProgress >= 100) {
        this.previewStatus = 'success'
      } else {
        this.previewStatus = this.isPreviewPlaying ? 'active' : 'normal'
      }
    },

    // 显示选中的航线
    showRoute (route) {
      this.clearWaypoints()
      this.routeName = route.name
      this.waypoints = [...route.waypoints]
      // 在地图上显示航线
      this.displayRouteOnMap(route)
    },

    // 执行航线
    executeRoute (route) {
      if (!this.map) return

      // 检查航线是否已在执行中
      const existingTask = this.activeExecutions.find(task => task.routeId === route.id)
      if (existingTask) {
        this.$message.warning(`航线 "${route.name}" 已在执行中`)
        return
      }

      // 创建执行任务
      const task = {
        id: Date.now().toString(),
        routeId: route.id, // 添加关联的航线ID
        name: route.name,
        waypoints: [...route.waypoints],
        currentPoint: 0,
        totalPoints: route.waypoints.length,
        currentTime: 0,
        totalTime: this.calculateTotalExecutionTime(route),
        status: 'executing',
        paused: false,
        speed: route.speed || this.droneSpeed, // 使用航线保存的速度或默认速度
        altitude: route.waypoints[0].altitude || 100,
        startTime: Date.now()
      }

      // 添加到活动执行任务列表
      this.activeExecutions.push(task)

      // 更新航线状态
      route.status = 'executing'

      // 保存到本地存储
      this.saveRoutesToStorage()

      // 在地图上绘制执行路线
      this.drawExecutionRoute(task)

      // 创建无人机标记
      this.createDroneMarker(task)

      // 开始执行任务
      this.startExecution(task)

      this.$message.success(`开始执行航线: ${route.name}`)
    },

    // 在地图上绘制执行路线
    drawExecutionRoute (task) {
      if (!this.map) return

      // 创建路径点数组
      const path = task.waypoints.map(point => {
        return new AMap.LngLat(point.lng, point.lat)
      })

      // 创建折线
      const polyline = new AMap.Polyline({
        path: path,
        strokeColor: '#3498db', // 线颜色
        strokeOpacity: 0.8, // 线透明度
        strokeWeight: 4, // 线宽
        strokeStyle: 'solid', // 线样式
        lineJoin: 'round', // 折线拐点连接处样式
        lineCap: 'round' // 折线两端线帽样式
      })

      // 将折线添加到地图
      this.map.add(polyline)

      // 保存折线引用
      this.executionPolylines[task.id] = polyline

      // 调整地图视野以包含整个路线
      this.map.setFitView([polyline])
    },

    // 创建无人机标记
    createDroneMarker (task) {
      if (!this.map || !task.waypoints.length) return

      // 获取起始点
      const startPoint = task.waypoints[0]

      try {
        // 创建标记
        const marker = new AMap.Marker({
          position: new AMap.LngLat(startPoint.lng, startPoint.lat),
          icon: new AMap.Icon({
            // 使用 public 目录下的图标
            image: '/drone-icon.png',
            size: new AMap.Size(32, 32),
            imageSize: new AMap.Size(32, 32)
          }),
          offset: new AMap.Pixel(-16, -16), // 图标中心点偏移
          autoRotation: true, // 自动旋转
          angle: 0, // 初始角度
          zIndex: 110 // 确保在其他标记之上
        })

        // 添加到地图
        this.map.add(marker)

        // 保存标记引用
        this.droneMarkers[task.id] = marker

        // 调整地图视野以包含起始点
        this.map.setZoomAndCenter(15, [startPoint.lng, startPoint.lat])

        return marker
      } catch (error) {
        console.error('创建无人机标记失败:', error)
        return null
      }
    },

    // 开始执行任务
    startExecution (task) {
      // 创建定时器，模拟无人机飞行
      const interval = setInterval(() => {
        if (task.paused) return // 如果暂停，不更新

        // 更新当前时间
        task.currentTime += 1

        // 计算当前应该到达的航点
        const totalDistance = this.calculateTotalDistance(task.waypoints)
        // 删除未使用的 speed 变量，或者在计算中使用它
        // const speed = task.speed || this.droneSpeed
        const expectedDistance = (task.currentTime / task.totalTime) * totalDistance

        // 找到当前应该在的航点段
        let accumulatedDistance = 0
        let currentSegment = 0
        let segmentProgress = 0

        for (let i = 0; i < task.waypoints.length - 1; i++) {
          const start = new AMap.LngLat(task.waypoints[i].lng, task.waypoints[i].lat)
          const end = new AMap.LngLat(task.waypoints[i + 1].lng, task.waypoints[i + 1].lat)
          const segmentDistance = start.distance(end)

          if (accumulatedDistance + segmentDistance >= expectedDistance) {
            currentSegment = i
            segmentProgress = (expectedDistance - accumulatedDistance) / segmentDistance
            break
          }

          accumulatedDistance += segmentDistance
        }

        // 更新当前航点
        task.currentPoint = currentSegment

        // 计算当前位置
        const start = task.waypoints[currentSegment]
        const end = task.waypoints[currentSegment + 1] || task.waypoints[currentSegment]

        // 线性插值计算当前位置
        const currentLng = parseFloat(start.lng) +
          (parseFloat(end.lng) - parseFloat(start.lng)) * segmentProgress

        const currentLat = parseFloat(start.lat) +
          (parseFloat(end.lat) - parseFloat(start.lat)) * segmentProgress

        // 计算航向角度
        const angle = this.calculateAngle(
          new AMap.LngLat(start.lng, start.lat),
          new AMap.LngLat(end.lng, end.lat)
        )

        // 更新无人机标记位置和角度
        const droneMarker = this.droneMarkers[task.id]
        if (droneMarker) {
          droneMarker.setPosition([currentLng, currentLat])
          droneMarker.setAngle(angle)
        }

        // 检查是否完成
        if (task.currentTime >= task.totalTime) {
          this.completeTask(task)
        }
      }, 1000) // 每秒更新一次

      // 保存定时器引用
      this.executionIntervals[task.id] = interval
    },

    // 添加计算航向角度的方法
    calculateAngle (start, end) {
      const dLng = end.getLng() - start.getLng()
      const dLat = end.getLat() - start.getLat()

      // 计算角度（弧度）
      let angle = Math.atan2(dLng, dLat)

      // 转换为度数
      angle = angle * (180 / Math.PI)

      // 调整为0-360度范围
      if (angle < 0) {
        angle += 360
      }

      return angle
    },

    // 完成任务
    completeTask (task) {
      // 清除定时器
      if (this.executionIntervals[task.id]) {
        clearInterval(this.executionIntervals[task.id])
        delete this.executionIntervals[task.id]
      }

      // 更新任务状态
      task.status = 'completed'

      // 更新对应航线的状态
      const route = this.routeList.find(r => r.id === task.routeId)
      if (route) {
        route.status = 'completed'
        this.saveRoutesToStorage()
      }

      // 从活动执行列表中移除
      this.activeExecutions = this.activeExecutions.filter(t => t.id !== task.id)

      // 清除地图上的无人机标记和路线
      this.clearExecutionGraphics(task.id)

      this.$message.success(`航线 ${task.name} 执行完成`)
    },

    // 显示航线
    displayRouteOnMap (route) {
      this.clearWaypoints()
      this.routeName = route.name
      this.waypoints = [...route.waypoints]

      // 在地图上显示航线
      this.waypoints.forEach(point => {
        const marker = new AMap.Marker({
          position: [point.lng, point.lat],
          label: {
            content: `航点${point.id}\n${point.altitude}米`,
            direction: 'top'
          }
        })
        this.markers.push(marker)
        this.map.add(marker)
      })

      // 绘制航线
      if (this.waypoints.length >= 2) {
        const path = this.waypoints.map(point => [point.lng, point.lat])
        this.polyline = new AMap.Polyline({
          path,
          strokeColor: '#3366FF',
          strokeWeight: 4,
          strokeStyle: 'solid',
          showDir: true
        })
        this.map.add(this.polyline)
      }

      // 调整地图视野以显示整条航线
      this.map.setFitView([...this.markers])
    },

    // 处理搜索
    handleSearch (value) {
      this.searchKeyword = value
    },

    // 处理过滤
    handleFilter (value) {
      this.filterStatus = value
    },

    // 添加回 formatTime 方法
    formatTime (seconds) {
      if (!seconds && seconds !== 0) return '00:00'
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = Math.floor(seconds % 60)
      return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`
    },

    // 获取状态颜色
    getStatusColor (status) {
      const colors = {
        draft: 'blue',
        executing: 'gold',
        completed: 'green',
        failed: 'red'
      }
      return colors[status] || 'default'
    },

    // 获取状态文本
    getStatusText (status) {
      const texts = {
        draft: '草稿',
        executing: '执行中',
        completed: '已完成',
        failed: '失败'
      }
      return texts[status] || '未知'
    },

    // 删除航线
    deleteRoute (route) {
      this.$confirm({
        title: '确认删除',
        content: `确定要删除航线 "${route.name}" 吗？`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          // 如果航线正在执行，先停止执行
          if (route.status === 'executing') {
            const task = this.activeExecutions.find(t => t.routeId === route.id)
            if (task) {
              this.stopTask(task)
            }
          }

          // 从列表中移除
          this.routeList = this.routeList.filter(r => r.id !== route.id)

          // 保存到本地存储
          this.saveRoutesToStorage()

          this.$message.success(`已删除航线: ${route.name}`)
        }
      })
    },

    // 保存航线到本地存储
    saveRoutesToStorage () {
      try {
        localStorage.setItem('routeList', JSON.stringify(this.routeList))
      } catch (error) {
        console.error('保存航线失败:', error)
      }
    },

    // 添加重置表单的方法
    resetForm () {
      // 清空航线名称
      this.routeName = ''

      // 清空航点列表
      this.clearWaypoints()

      // 重置无人机速度为默认值
      this.droneSpeed = 5

      // 重置其他相关状态
      this.nextWaypointId = 1
    },

    // 修改添加航点的方法，确保正确递增 ID
    addWaypoint (position) {
      // 更新航点列表，添加高度和悬停时间
      this.waypoints.push({
        id: this.nextWaypointId,
        lng: position.getLng().toFixed(6),
        lat: position.getLat().toFixed(6),
        altitude: 100, // 默认高度100米
        hoverTime: 0 // 默认悬停0秒
      })

      // 递增 ID
      this.nextWaypointId++

      // 其他代码不变
    },

    // 添加清除执行图形的方法
    clearExecutionGraphics (taskId) {
      // 清除无人机标记
      if (this.droneMarkers[taskId]) {
        this.map.remove(this.droneMarkers[taskId])
        delete this.droneMarkers[taskId]
      }

      // 清除执行路线
      if (this.executionPolylines[taskId]) {
        this.map.remove(this.executionPolylines[taskId])
        delete this.executionPolylines[taskId]
      }
    },

    // 计算总执行时间
    calculateTotalExecutionTime (route) {
      if (!route || !route.waypoints || route.waypoints.length < 2) return 0

      const totalDistance = this.calculateTotalDistance(route.waypoints)
      const speed = route.speed || this.droneSpeed // 使用航线保存的速度或默认速度

      // 计算飞行时间（距离/速度）
      const flightTime = totalDistance / speed

      // 假设每个航点停留5秒
      const hoverTime = route.waypoints.length * 5

      return flightTime + hoverTime
    },

    // 计算总飞行距离
    calculateTotalDistance (points) {
      if (!points || points.length < 2) return 0

      let totalDistance = 0
      for (let i = 0; i < points.length - 1; i++) {
        const start = new AMap.LngLat(points[i].lng, points[i].lat)
        const end = new AMap.LngLat(points[i + 1].lng, points[i + 1].lat)
        totalDistance += start.distance(end)
      }

      return totalDistance
    },

    // 计算进度
    calculateProgress (task) {
      if (!task.totalTime) return 0
      return Math.min(100, Math.round((task.currentTime / task.totalTime) * 100))
    },

    // 获取进度状态
    getProgressStatus (task) {
      if (task.status === 'failed') return 'exception'
      if (task.status === 'completed') return 'success'
      if (task.status === 'paused') return 'normal'
      return 'active'
    },

    // 获取执行状态颜色
    getExecutionStatusColor (task) {
      const colors = {
        executing: '#1890ff', // 蓝色
        paused: '#faad14', // 黄色
        completed: '#52c41a', // 绿色
        failed: '#f5222d', // 红色
        stopped: '#d9d9d9' // 灰色
      }
      return colors[task.status] || '#d9d9d9'
    },

    // 获取执行状态文本
    getExecutionStatusText (task) {
      const texts = {
        executing: '执行中',
        paused: '已暂停',
        completed: '已完成',
        failed: '失败',
        stopped: '已停止'
      }
      return texts[task.status] || '未知'
    },

    // 计算剩余时间
    calculateRemainingTime (task) {
      if (!task || !task.totalTime) return 0
      return Math.max(0, task.totalTime - task.currentTime)
    },

    // 计算预计到达时间
    calculateEstimatedArrivalTime (task) {
      if (!task || !task.startTime || !task.totalTime) return '未知'

      const startTime = new Date(task.startTime)
      const remainingSeconds = this.calculateRemainingTime(task)
      const arrivalTime = new Date(startTime.getTime() + (remainingSeconds * 1000))

      return this.formatDateTime(arrivalTime)
    },

    // 格式化日期时间
    formatDateTime (date) {
      if (!date) return ''

      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')

      return `${hours}:${minutes}:${seconds}`
    },

    // 格式化日期
    formatDateFull (dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    },

    // 停止任务
    stopTask (task) {
      // 清除定时器
      if (this.executionIntervals[task.id]) {
        clearInterval(this.executionIntervals[task.id])
        delete this.executionIntervals[task.id]
      }

      // 更新任务状态
      task.status = 'stopped'

      // 更新对应航线的状态
      const route = this.routeList.find(r => r.id === task.routeId)
      if (route) {
        route.status = 'draft' // 将状态设置回草稿，允许重新执行
        this.saveRoutesToStorage()
      }

      // 从活动执行列表中移除
      this.activeExecutions = this.activeExecutions.filter(t => t.id !== task.id)

      // 清除地图上的无人机标记和路线
      this.clearExecutionGraphics(task.id)

      this.$message.info(`已停止执行航线: ${task.name}`)
    },

    // 暂停/继续任务
    togglePause (task) {
      task.paused = !task.paused
      task.status = task.paused ? 'paused' : 'executing'

      // 更新对应航线的状态
      const route = this.routeList.find(r => r.id === task.routeId)
      if (route) {
        route.status = task.status
        this.saveRoutesToStorage()
      }

      this.$message.info(`${task.paused ? '已暂停' : '已继续'}执行航线: ${task.name}`)
    },

    // 初始化执行相关的数据
    initExecutionData () {
      // 确保在 data 中有这些属性
      if (!this.executionIntervals) {
        this.executionIntervals = {}
      }
      if (!this.activeExecutions) {
        this.activeExecutions = []
      }
    }
  },
  computed: {
    filteredRouteList () {
      if (!this.routeList || !Array.isArray(this.routeList)) {
        return []
      }

      return this.routeList
        .filter(route => {
          const matchesSearch = !this.searchKeyword ||
            route.name.toLowerCase().includes(this.searchKeyword.toLowerCase())
          const matchesFilter = !this.filterStatus ||
            route.status === this.filterStatus
          return matchesSearch && matchesFilter
        })
        .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
    }
  },
  beforeDestroy () {
    // 清理所有执行任务的定时器
    if (this.executionIntervals) {
      Object.values(this.executionIntervals).forEach(interval => {
        clearInterval(interval)
      })
    }

    // 确保清理预览相关资源
    this.stopPreview()
    if (this.map) {
      try {
        this.map.destroy()
      } catch (error) {
        console.error('销毁地图实例失败:', error)
      }
    }
  },
  watch: {
    // 监听 activeTab 变化
    activeTab (newVal) {
      if (newVal === '2') {
        // 切换到航线列表时刷新列表
        this.loading = true
        setTimeout(() => {
          this.loading = false
        }, 500)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.route-planning {
  display: flex;
  height: 600px;
  gap: 16px;

  .control-panel {
    width: 320px;
    overflow-y: auto;

    .section-title {
      font-weight: 500;
      margin-bottom: 16px;
    }

    .control-buttons {
      margin-top: 16px;
      display: flex;
      gap: 8px;
    }
  }

  .map-container {
    flex: 1;
    position: relative;

    .map {
      width: 100%;
      height: 100%;
    }

    .map-controls {
      position: absolute;
      top: 10px;
      left: 10px;
      z-index: 100;
      background: rgba(255, 255, 255, 0.9);
      padding: 10px;
      border-radius: 4px;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }

    .planning-tips {
      position: absolute;
      top: 10px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 100;
      min-width: 300px;
    }

    .error-message {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 80%;
      z-index: 100;
    }
  }

  // 添加预览控制面板样式
  .preview-controls {
    .preview-info {
      margin-bottom: 16px;

      p {
        margin-bottom: 8px;
      }

      .progress-wrapper {
        margin-top: 16px;

        .progress-text {
          text-align: center;
          margin-top: 8px;
          color: rgba(0, 0, 0, 0.45);
        }
      }
    }

    .preview-buttons {
      text-align: center;
    }
  }

  // 添加新样式
  .execution-controls {
    .execution-info {
      margin-bottom: 16px;

      h4 {
        margin-bottom: 16px;
        font-weight: 500;
      }

      .execution-status {
        margin-top: 16px;
        padding: 8px;
        background: #f5f5f5;
        border-radius: 4px;

        p {
          margin-bottom: 4px;
          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }

    .execution-buttons {
      text-align: center;
    }
  }

  // 添加新样式
  .list-header {
    margin-bottom: 16px;
    display: flex;
    gap: 8px;
  }

  .route-header {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .route-name {
      font-weight: 500;
      font-size: 16px;
    }
  }

  .route-info {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
    margin: 8px 0;

    .info-item {
      display: flex;
      align-items: center;
      gap: 8px;
      color: rgba(0, 0, 0, 0.65);

      .anticon {
        color: #1890ff;
      }
    }
  }

  // 执行信息覆盖层
  .execution-info-overlay {
    position: absolute;
    bottom: 20px;
    right: 20px;
    max-width: 300px;
    z-index: 100;

    .execution-info-card {
      background-color: rgba(255, 255, 255, 0.9);
      border-radius: 4px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      padding: 12px;
      margin-bottom: 10px;

      .execution-info-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        span {
          font-weight: 500;
        }
      }

      .execution-info-progress {
        margin-bottom: 8px;
      }

      .execution-info-details {
        display: flex;
        justify-content: space-between;
        font-size: 12px;
        color: rgba(0, 0, 0, 0.65);
        margin-bottom: 8px;
      }

      .execution-info-actions {
        text-align: right;
      }
    }
  }

  // 航线列表容器
  .route-list-container {
    display: flex;
    gap: 16px;

    .route-list {
      flex: 1;
      min-width: 0; // 防止内容溢出
    }

    .execution-list {
      width: 300px;
      border-left: 1px solid #f0f0f0;
      padding-left: 16px;

      .execution-header {
        margin-bottom: 16px;

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 500;
        }
      }

      .execution-item {
        .execution-title {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 8px;

          .name {
            font-weight: 500;
          }
        }

        .execution-progress {
          margin-bottom: 8px;

          .progress-details {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            color: rgba(0, 0, 0, 0.45);
            margin-top: 4px;
          }
        }

        .execution-status {
          margin-bottom: 8px;
          font-size: 12px;
          color: rgba(0, 0, 0, 0.65);

          p {
            margin-bottom: 4px;
            &:last-child {
              margin-bottom: 0;
            }
          }
        }

        .execution-actions {
          text-align: right;
        }
      }
    }
  }
}

.flight-details {
  margin-top: 8px;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.65);

  .detail-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;

    .label {
      color: rgba(0, 0, 0, 0.45);
    }

    .value {
      font-weight: 500;
    }
  }
}

.execution-info-details {
  .detail-row {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: rgba(0, 0, 0, 0.65);
    margin-bottom: 4px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

// 删除执行任务列表的样式
.execution-list {
  display: none; // 或者完全删除这个样式块
}

// 保留地图上的执行任务卡片样式
.map-progress-card {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 12px;
  max-width: 300px;
  z-index: 100;

  .task-progress-item {
    margin-bottom: 12px;

    &:last-child {
      margin-bottom: 0;
    }

    .task-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;

      .task-name {
        font-weight: 500;
      }
    }

    .task-progress {
      margin-bottom: 8px;
    }

    .task-info {
      display: flex;
      justify-content: space-between;
      font-size: 12px;
      color: rgba(0, 0, 0, 0.65);
      margin-bottom: 8px;
    }

    .task-actions {
      text-align: right;
    }
  }
}
</style>
